package com.kob.backend.consumer.utils;

import java.util.Random;

public class Game {
    final private Integer rows;
    final private Integer cols;
    final private Integer inner_walls_count;
    final private int[][] g;
    final private static int[] dx={-1,0,1,0}, dy={0,1,0,-1};

    public Game(Integer rows, Integer cols, Integer inner_walls_count){
        this.rows = rows;
        this.cols = cols;
        this.inner_walls_count = inner_walls_count;
        this.g = new int[rows][cols];
    }
    public int[][] getG(){
        return g;
    }
    private boolean check_connectivity(int sx, int sy, int tx, int ty){
        if(sx==tx && sy==ty) return true;
        g[sx][sy]=1;//标记走过了
        for(int i=0; i<4; i++){
            int x=sx+dx[i], y=sy+dy[i];
            if(x>=0 && x<this.rows && y>=0 && y<this.cols && g[x][y]==0) {
                if(check_connectivity(x, y, tx, ty)){
                    g[sx][sy]=0;//恢复现场
                    return true;//如果没撞墙并且能走到终点的话，返回true
                }
            }
        }
        g[sx][sy]=0;//因为在后端的g是全局变量，所以要恢复现场
        return false;
    }
    private boolean draw(){//画地图
        for (int i = 0; i < this.rows; i++) {
            for (int j = 0; j < this.cols; j++) {
                g[i][j]=0;
            }
        }
        for(int r=0; r<this.rows; r++){//四周加上墙
            g[r][0]=g[r][this.cols-1]=1;
        }
        for(int c=0; c<this.cols; c++){
            g[0][c]=g[this.rows-1][c]=1;
        }
        Random random = new Random();
        for (int i = 0; i < this.inner_walls_count/2; i++) {
            for (int j = 0; j < 1000; j++) {
                int r=random.nextInt(this.rows);//返回一个[0, rows)的随机数
                int c=random.nextInt(this.cols);
                if(g[r][c]==1||g[this.rows-1-r][this.cols-1-c]==1) continue;//这个位置有墙
                if(r==this.rows-2 && c==1 || r==1 && c==this.cols-2) continue;//不能放在左下角和右上角
                g[r][c]=g[this.rows-1-r][this.cols-1-c]=1; //在(r,c)和(c,r)位置都设置为true
                break;
            }
        }
        return check_connectivity(this.rows-2, 1, 1, this.cols-2);//检查是否连通
    }
    public void createMap(){
        for (int i = 0; i < 1000; i++) {
            if(draw()) break; // 如果成功，则结束画地图
        }
    }
}
